<template>
  <div class="superior-plan-entry bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">上级预案录入</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="planCode" class="block text-sm font-medium">预案编码：</label>
          <input type="text" id="planCode" v-model="search.plan_code" placeholder="请输入"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
        </div>
        <div>
          <label for="planName" class="block text-sm font-medium">预案名称：</label>
          <input type="text" id="planName" v-model="search.plan_name" placeholder="请输入"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
        </div>
        <div>
          <label for="planType" class="block text-sm font-medium">预案类别：</label>
          <select id="planType" v-model="search.plan_type"
            class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            <option value="">请选择</option>
            <option value="comprehensive">综合应急预案</option>
            <option value="special">专项应急预案</option>
            <option value="onsite">现场处置方案</option>
          </select>
        </div>
        <div class="flex justify-end mt-6">
          <button @click="searchPlans" class="bg-primary text-primary-foreground px-4 py-2 rounded mr-2">查询</button>
          <button @click="resetSearch" class="bg-secondary text-secondary-foreground px-4 py-2 rounded">重置</button>
        </div>
      </div>
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <button @click="openAddDialog" class="bg-primary text-primary-foreground px-4 py-2 rounded">录入</button>
      <button @click="exportData" class="bg-secondary text-secondary-foreground px-4 py-2 rounded">导出</button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground shadow-md rounded my-6">
      <table class="min-w-full table-auto">
        <thead>
          <tr class="bg-muted text-muted-foreground uppercase text-sm leading-normal">
            <th class="py-3 px-6 text-left">预案编码</th>
            <th class="py-3 px-6 text-left">预案名称</th>
            <th class="py-3 px-6 text-left">编制单位</th>
            <th class="py-3 px-6 text-left">预案类别</th>
            <th class="py-3 px-6 text-left">事故类型</th>
            <th class="py-3 px-6 text-left">发布时间</th>
            <!-- <th class="py-3 px-6 text-left">操作</th> -->
          </tr>
        </thead>
        <tbody class="text-sm">
          <tr v-for="item in displayedPlanData" :key="item.id" class="border-b border-border hover:bg-muted/50">
            <td class="py-3 px-6 text-left">{{ item.plan_code }}</td>
            <td class="py-3 px-6 text-left">{{ item.plan_name }}</td>
            <td class="py-3 px-6 text-left">{{ item.organization }}</td>
            <td class="py-3 px-6 text-left">{{ item.plan_type }}</td>
            <td class="py-3 px-6 text-left">{{ item.accident_type }}</td>
            <td class="py-3 px-6 text-left">{{ item.publish_time }}</td>
            <!-- <td class="py-3 px-6 text-left">
              <button @click="viewDetails(item)" class="text-primary hover:text-primary/80 mr-2">查看</button>
            </td> -->
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <div class="flex items-center justify-between">
      <div class="flex items-center">
        <span class="mr-2">每页显示</span>
        <select v-model="pageSize" @change="changePageSize"
          class="rounded border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
          <option :value="10">10</option>
          <option :value="20">20</option>
          <option :value="50">50</option>
        </select>
        <span class="ml-2">条</span>
      </div>
      <div class="flex items-center">
        <button @click="prevPage" :disabled="currentPage === 1"
          class="px-3 py-1 rounded bg-secondary text-secondary-foreground mr-1">&lt;</button>
        <button v-for="page in displayedPages" :key="page" @click="goToPage(page)"
          :class="['px-3', 'py-1', 'rounded', 'mr-1', currentPage === page ? 'bg-primary text-primary-foreground' : 'bg-secondary text-secondary-foreground']">
          {{ page }}
        </button>
        <button @click="nextPage" :disabled="currentPage === totalPages"
          class="px-3 py-1 rounded bg-secondary text-secondary-foreground ml-1">&gt;</button>
        <span class="ml-2">跳至</span>
        <input v-model.number="jumpToPage" @keyup.enter="goToPage(jumpToPage)" type="number" min="1" :max="totalPages"
          class="w-16 rounded border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50 mx-2">
        <span>页</span>
      </div>
    </div>

    <!-- Add Plan Dialog -->
    <div v-if="isAddDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">上级预案录入</h3>
          <button @click="closeAddDialog" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div class="mb-4">
          <h4 class="font-bold mb-2">基本信息</h4>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="newPlanCode" class="block text-sm font-medium">预案编码：</label>
              <input type="text" id="newPlanCode" v-model="newRecord.plan_code"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            </div>
            <div>
              <label for="newPlanName" class="block text-sm font-medium">预案名称：</label>
              <input type="text" id="newPlanName" v-model="newRecord.plan_name"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            </div>
            <div>
              <label for="newPlanType" class="block text-sm font-medium">预案类别：</label>
              <select id="newPlanType" v-model="newRecord.plan_type"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
                <option value="">请选择</option>
                <option value="comprehensive">综合应急预案</option>
                <option value="special">专项应急预案</option>
                <option value="onsite">现场处置方案</option>
              </select>
            </div>
            <div>
              <label for="newOrganization" class="block text-sm font-medium">编制单位：</label>
              <input type="text" id="newOrganization" v-model="newRecord.organization"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            </div>
            <div>
              <label for="newAccidentType" class="block text-sm font-medium">事故类型：</label>
              <input type="text" id="newAccidentType" v-model="newRecord.accident_type"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            </div>
            <div>
              <label for="newPublishTime" class="block text-sm font-medium">发布时间：</label>
              <input type="datetime-local" id="newPublishTime" v-model="newRecord.publish_time"
                class="mt-1 block w-full rounded-md border-input bg-background shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50">
            </div>
          </div>
        </div>

        <div class="mb-4">
          <h4 class="font-bold mb-2">附件</h4>
          <div class="flex items-center space-x-2">
            <input type="file" @change="handleFileUpload" accept=".pdf,.doc,.docx" class="hidden" ref="fileInput"
              multiple>
            <button @click="$refs.fileInput.click()"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/80 focus:outline-none focus:ring-2 focus:ring-primary/40">
              上传文件
            </button>
          </div>
          <div v-if="newRecord.plan_files && newRecord.plan_files.length > 0" class="mt-2">
            <div v-for="(file, index) in newRecord.plan_files" :key="index"
              class="flex items-center justify-between bg-muted/50 p-2 rounded mb-2">
              <span>{{ file.name }}</span>
              <button @click="removeFile(index)" class="text-destructive hover:text-destructive/80">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                  xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>

        <div class="flex justify-end space-x-2 mt-6">
          <button @click="closeAddDialog"
            class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-secondary/40">
            取消
          </button>
          <button @click="addNewPlan"
            class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/80 focus:outline-none focus:ring-2 focus:ring-primary/40">
            提交
          </button>
        </div>
      </div>
    </div>

    <!-- View Details Dialog -->
    <div v-if="isViewDialogOpen" class="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
      <div class="bg-card text-card-foreground p-5 rounded-lg shadow-xl w-[800px]">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">查看上级预案详情</h3>
          <button @click="closeViewDialog" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>
        <div v-if="selectedItem" class="grid grid-cols-2 gap-4">
          <div v-for="(value, key) in selectedItem" :key="key">
            <strong>{{ getChineseFieldName(key) }}:</strong> {{ formatFieldValue(key, value) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api/superior-plan-entry')

// 搜索相关
const search = ref({
  plan_code: '',
  plan_name: '',
  plan_type: ''
})

// 数据相关
const planData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)

// 对话框状态
const isAddDialogOpen = ref(false)
const isViewDialogOpen = ref(false)

// 新记录
const newRecord = ref({
  plan_code: '',
  plan_name: '',
  plan_type: '',
  organization: '',
  accident_type: '',
  publish_time: '',
  plan_files: []
})

const selectedItem = ref(null)

// 计算属性
const totalItems = computed(() => planData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const displayedPages = computed(() => {
  const range = 2
  const start = Math.max(1, currentPage.value - range)
  const end = Math.min(totalPages.value, currentPage.value + range)
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

const displayedPlanData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return planData.value.slice(start, end)
})

// API 调用函数
const searchPlans = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    planData.value = response.data
  } catch (error) {
    console.error('搜索上级预案记录失败:', error)
    alert('搜索上级预案记录失败')
  }
}

const addNewPlan = async () => {
  try {
    const formData = new FormData()
    for (const key in newRecord.value) {
      if (key !== 'plan_files') {
        formData.append(key, newRecord.value[key])
      }
    }
    newRecord.value.plan_files.forEach((file, index) => {
      formData.append(`plan_files[${index}]`, file)
    })

    const response = await axios.post(apiBaseUrl.value, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    alert(response.data.message || '创建上级预案成功')
    closeAddDialog()
    await searchPlans()
  } catch (error) {
    console.error('创建上级预案记录失败:', error)
    alert('创建上级预案记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 事件处理函数
const resetSearch = () => {
  search.value = {
    plan_code: '',
    plan_name: '',
    plan_type: ''
  }
  searchPlans()
}

const openAddDialog = () => {
  newRecord.value = {
    plan_code: '',
    plan_name: '',
    plan_type: '',
    organization: '',
    accident_type: '',
    publish_time: '',
    plan_files: []
  }
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
}

const handleFileUpload = (event) => {
  newRecord.value.plan_files = Array.from(event.target.files)
}

const removeFile = (index) => {
  newRecord.value.plan_files.splice(index, 1)
}

const exportData = () => {
  const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(planData.value))
  const downloadAnchorNode = document.createElement('a')
  downloadAnchorNode.setAttribute("href", dataStr)
  downloadAnchorNode.setAttribute("download", "superior_plan_data.json")
  document.body.appendChild(downloadAnchorNode)
  downloadAnchorNode.click()
  downloadAnchorNode.remove()
}

const changePageSize = () => {
  currentPage.value = 1
  searchPlans()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    searchPlans()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    searchPlans()
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    searchPlans()
  }
}

const viewDetails = (item) => {
  selectedItem.value = { ...item }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = null
}

// 字段名称映射
const fieldNameMap = {
  id: 'ID',
  plan_code: '预案编码',
  plan_name: '预案名称',
  organization: '编制单位',
  plan_type: '预案类别',
  accident_type: '事故类型',
  publish_time: '发布时间'
}

// 获取中文字段名
const getChineseFieldName = (key) => {
  return fieldNameMap[key] || key
}

// 格式化字段值
const formatFieldValue = (key, value) => {
  if (key === 'publish_time' && value) {
    return new Date(value).toLocaleString('zh-CN')
  }
  if (key === 'plan_type') {
    const planTypeMap = {
      'comprehensive': '综合应急预案',
      'special': '专项应急预案',
      'onsite': '现场处置方案'
    }
    return planTypeMap[value] || value
  }
  return value
}

// 生命周期钩子
onMounted(() => {
  searchPlans()
})
</script>

<style scoped>
.container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.search-form {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.form-item {
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.form-item label {
  margin-right: 5px;
}

.form-item input,
.form-item select {
  padding: 5px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  width: 200px;
}

.search-btn,
.reset-btn {
  padding: 6px 15px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-btn {
  background-color: #1890ff;
  color: white;
}

.reset-btn {
  background-color: white;
  color: #333;
  border: 1px solid #d9d9d9;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-btn {
  margin-right: 10px;
  padding: 6px 15px;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  border: 1px solid #e8e8e8;
  padding: 12px 8px;
  text-align: left;
}

.data-table th {
  background-color: #fafafa;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #fafafa;
}

.action-link {
  color: #1890ff;
  text-decoration: none;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.page-buttons {
  display: flex;
}

.page-btn {
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  cursor: pointer;
}

.page-btn.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}
</style>
